package com.ikun.admin.modules.scheduled.quartz;

import com.ikun.admin.modules.scheduled.entity.Task;
import com.ikun.admin.modules.scheduled.entity.TaskLog;
import com.ikun.admin.modules.scheduled.service.TaskLogService;
import com.ikun.common.exception.ExceptionUtils;
import com.ikun.common.utils.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * @ClassName MyScheduleJob
 * @Description: 定时任务 执行器
 * @CreateDate: 2024/8/11 23:03
 */
@Slf4j
public class MyScheduleJob extends QuartzJobBean {
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        //获取:任务实体信息
        Task taskInfo = (Task) context.getMergedJobDataMap().
                get(Constant.JOB_KEY);
        //数据库保存执行记录


        TaskLog taskLog = new TaskLog();
        taskLog.setTaskId(taskInfo.getId());
        taskLog.setCreateTime(LocalDateTime.now());
        //任务开始时间
        long startTime = System.currentTimeMillis();

        try {
            //执行任务
            log.info("任务准备执行，任务ID：{}", taskInfo.getId());
            Object target = SpringContextUtils.getBean(taskInfo.getTaskBean());
            Method method = target.getClass().getDeclaredMethod("run", String.class);
            method.invoke(target, taskInfo.getParams());
            //任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            taskLog.setTimes((int) times);
            //任务状态
            taskLog.setStatus(Constant.JOB_STATUS_SUCCESS);

            log.info("任务执行完毕，任务ID：{}  总共耗时：{} 毫秒", taskInfo.getId(), times);
        } catch (Exception e) {
            log.error("任务执行失败，任务ID：{}", taskInfo.getId(), e);
            //任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            taskLog.setTimes((int) times);

            //任务状态
            taskLog.setStatus(Constant.JOB_STATUS_FAIL);
            taskLog.setError(ExceptionUtils.getErrorStackTrace(e));
        } finally {
            //获取记录日志
            TaskLogService taskLogService = SpringContextUtils.getBean(TaskLogService.class);
            taskLogService.save(taskLog);
        }
    }
}
